package org.dding.core.mx;

import java.util.Hashtable;

import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class MBeanUtils {

	private static JMXServiceURL jmxUrl;
	private static JMXConnector connector;
	private static MBeanServerConnection mBeanServerconnection;

	private static void createJMXRmiConnector(String serverHost,
			String namingHost, int namingPort) throws Exception {
		// 1.The JMXConnectorServer protocol
		String serverProtocol = "rmi";

		String jndiPath = "/connector";

		// 4. connector server url
		jmxUrl = new JMXServiceURL("service:jmx:" + serverProtocol + "://"
				+ serverHost + "/jndi/rmi://" + namingHost + ":" + namingPort
				+ jndiPath);

		// 5. 生成 JMXConnector,连接到url一端
		// Connect a JSR 160 JMXConnector to the server side
		connector = JMXConnectorFactory.connect(jmxUrl);
		mBeanServerconnection = connector.getMBeanServerConnection();
	}

	public static <T extends Object> T getBean(String serverHost,
			String namingHost, int namingPort, String domain,
			Hashtable<String, String> hashtable, Class<T> clazz)
			throws Throwable {

		ObjectName objectName = new ObjectName(domain, hashtable);

		createJMXRmiConnector(serverHost, namingHost, namingPort);

		T proxy = MBeanServerInvocationHandler.newProxyInstance(
				mBeanServerconnection, objectName, clazz, true);
		return proxy;
	}
}
